package com.svtar.ywg.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.svtar.ywg.MyApp;
import com.svtar.ywg.R;
import com.svtar.ywg.api.Api;
import com.svtar.ywg.api.SimpleCallback;
import com.svtar.ywg.constant.MyConstant;
import com.svtar.ywg.ui.base.BaseFragment;
import com.svtar.ywg.utils.SharedPreferencesUtils;
import com.svtar.ywg.utils.ToastUitls;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Svtar on 2019/1/23.
 * 控制台
 */

public class ConsoleFragment extends BaseFragment implements View.OnClickListener {

    @BindView(R.id.web_view)
    WebView mWebView;
    @BindView(R.id.multiple_actions)
    FloatingActionsMenu mMultipleActions;
    @BindView(R.id.action_key)
    FloatingActionButton mActionKey;
    private String cookie = "";

    @Override
    protected void init() {
        //检查是否设置密钥
        if (TextUtils.isEmpty((String) SharedPreferencesUtils.getInstance().getData("systemApi", ""))) {
            mActionKey.performClick();
        }
        initWebView();
        mWebView.loadUrl(MyConstant.LOGIN_URL);
    }

    @Override
    protected View setContentView(LayoutInflater inflater) {
        View view = inflater.inflate(R.layout.fragment_console, null);
        return view;
    }

    @OnClick({ R.id.action_key, R.id.action_user, R.id.action_merchant})
    @Override
    public void onClick(View view) {
        mMultipleActions.toggle();
        switch (view.getId()) {
            case R.id.action_user:
                //上传用户凭证
                if (!TextUtils.isEmpty(cookie)) {
                    final AlertDialog alertDialogSave = new AlertDialog.Builder(getActivity())
                            .setView(R.layout.dialog_svae)
                            .show();
                    alertDialogSave.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!TextUtils.isEmpty(((EditText) alertDialogSave.findViewById(R.id.et_mobile)).getText().toString().trim())) {
                                //TODO 上传用户到服务器
                                //清除所有保存的Cookie
                                CookieManager cookieManager = CookieManager.getInstance();
                                cookieManager.setAcceptCookie(true);
                                cookieManager.removeSessionCookie();
                                cookieManager.removeAllCookie();
                                //跳转到登陆页
                                mWebView.loadUrl(MyConstant.LOGIN_URL);
                                alertDialogSave.dismiss();
                            } else {
                                ToastUitls.showToast(getActivity(), "请填写手机号!");
                            }
                        }
                    });
                    alertDialogSave.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialogSave.dismiss();
                        }
                    });
                } else {
                    ToastUitls.showToast(MyApp.getInstance(), "请先登录义乌购！");
                }
                break;
            case R.id.action_merchant:
                //上传商户凭证
                if (!TextUtils.isEmpty(cookie)) {
                    final AlertDialog alertDialogSave = new AlertDialog.Builder(getActivity())
                            .setView(R.layout.dialog_svae)
                            .show();
                    alertDialogSave.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!TextUtils.isEmpty(((EditText) alertDialogSave.findViewById(R.id.et_mobile)).getText().toString().trim())) {
                                //TODO 上传商户到服务器
                                //清除所有保存的Cookie
                                CookieManager cookieManager = CookieManager.getInstance();
                                cookieManager.setAcceptCookie(true);
                                cookieManager.removeSessionCookie();
                                cookieManager.removeAllCookie();
                                //跳转到登陆页
                                mWebView.loadUrl(MyConstant.LOGIN_URL);
                                alertDialogSave.dismiss();
                            } else {
                                ToastUitls.showToast(getActivity(), "请填写手机号!");
                            }
                        }
                    });
                    alertDialogSave.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            alertDialogSave.dismiss();
                        }
                    });
                } else {
                    ToastUitls.showToast(MyApp.getInstance(), "请先登录义乌购！");
                }
                break;
            case R.id.action_key:
                final AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                        .setView(R.layout.dialog_key)
                        .show();
                if (!TextUtils.isEmpty((String) SharedPreferencesUtils.getInstance().getData("systemApi", ""))) {
                    ((EditText) alertDialog.findViewById(R.id.et_api)).setText((String) SharedPreferencesUtils.getInstance().getData("systemApi", ""));
                }
                if (!TextUtils.isEmpty((String) SharedPreferencesUtils.getInstance().getData("systemId", ""))) {
                    ((EditText) alertDialog.findViewById(R.id.et_id)).setText((String) SharedPreferencesUtils.getInstance().getData("systemId", ""));
                }
                if (!TextUtils.isEmpty((String) SharedPreferencesUtils.getInstance().getData("systemKey", ""))) {
                    ((EditText) alertDialog.findViewById(R.id.et_key)).setText((String) SharedPreferencesUtils.getInstance().getData("systemKey", ""));
                }
                alertDialog.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!TextUtils.isEmpty(((EditText) alertDialog.findViewById(R.id.et_api)).getText().toString().trim()) &&
                                !TextUtils.isEmpty(((EditText) alertDialog.findViewById(R.id.et_id)).getText().toString().trim()) &&
                                !TextUtils.isEmpty(((EditText) alertDialog.findViewById(R.id.et_key)).getText().toString().trim())) {
                            final String systemApi = ((EditText) alertDialog.findViewById(R.id.et_api)).getText().toString().trim();
                            final String systemId = ((EditText) alertDialog.findViewById(R.id.et_id)).getText().toString().trim();
                            final String signKey = ((EditText) alertDialog.findViewById(R.id.et_key)).getText().toString().trim();
                            Api.getInstance().checkoutAttestation(new SimpleCallback(getActivity(), true) {
                                @Override
                                public void onSuccess(Response<String> response) {
                                    if (!TextUtils.isEmpty(response.body())) {
                                        Logger.e("签名验证：" + response.body());
                                        JSONObject jsonObject = JSON.parseObject(response.body());
                                        if (jsonObject.getInteger("code") == 0) {
                                            alertDialog.dismiss();
                                            SharedPreferencesUtils.getInstance().saveData("systemApi", systemApi);
                                            SharedPreferencesUtils.getInstance().saveData("systemId", systemId);
                                            SharedPreferencesUtils.getInstance().saveData("systemKey", signKey);
                                            ToastUitls.showToast(MyApp.getInstance(), "设置成功！");
                                        } else {
                                            ToastUitls.showToast(MyApp.getInstance(), jsonObject.getString("msg"));
                                        }
                                    }
                                }
                            }, systemApi, systemId, signKey);
                        } else {
                            ToastUitls.showToast(getActivity(), "请认真配置系统参数!");
                        }
                    }
                });
                alertDialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        alertDialog.dismiss();
                    }
                });
                break;
        }
    }


    /**
     * 初始化WebView控件
     */
    private void initWebView() {
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setUseWideViewPort(true);//设置webview推荐使用的窗口
        webSettings.setLoadWithOverviewMode(true);//设置webview加载的页面的模式
        webSettings.setDisplayZoomControls(false);//隐藏webview缩放按钮
        webSettings.setBuiltInZoomControls(true);// 设置显示缩放按钮
        webSettings.setSupportZoom(true);// 支持缩放
        webSettings.setAllowFileAccess(true); //允许访问文件
        webSettings.setJavaScriptEnabled(true); //设置支持javascript脚本
        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 开启 DOM storage API 功能
        webSettings.setDomStorageEnabled(true);
        //开启 database storage API 功能
        webSettings.setDatabaseEnabled(true);
        String cacheDirPath = getActivity().getFilesDir().getAbsolutePath() + "/webviewCache";
        //设置数据库缓存路径
        webSettings.setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webSettings.setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webSettings.setAppCacheEnabled(true);
        //设置Cookie
        CookieManager mCookieManager = CookieManager.getInstance();
        mCookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mCookieManager.setAcceptThirdPartyCookies(mWebView, true);
        }
        //主要用于平板，针对特定屏幕代码调整分辨率
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity == 240) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if (mDensity == 120) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        } else if (mDensity == DisplayMetrics.DENSITY_XHIGH) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == DisplayMetrics.DENSITY_TV) {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else {
            webSettings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        }

        /**
         * 用WebView显示图片，可使用这个参数 设置网页布局类型：
         * 1、LayoutAlgorithm.NARROW_COLUMNS ：适应内容大小
         * 2、LayoutAlgorithm.SINGLE_COLUMN:适应屏幕，内容将自动缩放
         */
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);

        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                CookieManager cookieManager = CookieManager.getInstance();
                cookie = cookieManager.getCookie(url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, final String url) {
                if (url == null) {
                    return false;
                }
                Logger.e("加载地址：" + url);
                try {
                    if (!url.startsWith("http://") && !url.startsWith("https://")) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                } catch (Exception e) {//防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                    return true;//没有安装该app时，返回true，表示拦截自定义链接，但不跳转，避免弹出上面的错误页面
                }
                //返回值是true的时候控制去WebView打开，为false调用系统浏览器或第三方浏览器
                mWebView.loadUrl(url);
                return true;
            }
        });
    }
}
